<template>
	<view class="im" :class='APPTheme' >
		<uni-nav-bar fixed status-bar title="消息列表" :color="APPTheme=='theme-light'?'#000000':'#ffffff'" :background-color="APPTheme=='theme-light'?'#ffffff':'#000000'"></uni-nav-bar>
		<scroll-view class="center" scroll-y="true" :refresher-background="APPTheme=='theme-light'?'#ffffff':'#000000'" :refresher-threshold="100" refresher-enabled :refresher-triggered="refres.isRefresher" @refresherrefresh="loadRefresh">
			<uni-swipe-action>
				<uni-swipe-action-item v-for="(item,index) in chatList" :key="item.uuid+Math.random()" v-if="item.isTop&&item.uuid!=showActionUuid" :options="action.options1" @click="actionItemClick($event,item)">
					<view class="center-list-item center-list-item-top theme-bg theme-bg-active theme-border-bottom-auto" @click="navigetTo(item)" v-if="item.isMsgShow==1">
						<view class="item-left">
							<u-avatar class="text-warp" v-if="item.userInfo&&item.userInfo.photo" :src="GLOBAL.image_svr+item.userInfo.photo"></u-avatar>
							<view class="text-warp" v-else>{{computedUserInfo(item.userInfo)}}</view>
						</view>
						<view class="item-right">
							<view class="item-right-top">
								<view class="top-title lz-ellipsis-1">{{item.userInfo&&item.userInfo.name}}</view>
								<view class="top-date">{{computeTime(item)}}</view>
							</view>
							<view class="item-right-bottom lz-ellipsis-1">
								<rich-text class="top-title lz-ellipsis-1" v-if="item.messageType=='text'" :nodes="JSON.parse(item.content).text"></rich-text>
								<view class="top-title lz-ellipsis-1" v-else>{{computeContent(item)}}</view>
								<uni-badge :text="item.count" type="error" size="small" bgColor=""></uni-badge>
							</view>
						</view>
					</view>
				</uni-swipe-action-item>
				<uni-swipe-action-item v-for="(item,index) in chatList" :key="item.uuid+Math.random()" v-if="!item.isTop&&item.uuid!=showActionUuid" :options="action.options"   @click="actionItemClick($event,item)">
					<view class="center-list-item theme-bg theme-bg-active theme-border-bottom-auto" @click="navigetTo(item)" v-if="item.isMsgShow==1">
						<view class="item-left">
							<u-avatar class="text-warp" v-if="item.userInfo&&item.userInfo.photo" :src="GLOBAL.image_svr+item.userInfo.photo"></u-avatar>
							<view class="text-warp" v-else>{{computedUserInfo(item.userInfo)}}</view>
						</view>
						<view class="item-right">
							<view class="item-right-top">
								<view class="top-title lz-ellipsis-1">{{item.userInfo&&item.userInfo.name}}</view>
								<view class="top-date">{{computeTime(item)}}</view>
							</view>
							<view class="item-right-bottom lz-ellipsis-1">
								<rich-text class="top-title lz-ellipsis-1" v-if="item.messageType=='text'" :nodes="JSON.parse(item.content).text"></rich-text>
								<view class="top-title lz-ellipsis-1" v-else>{{computeContent(item)}}</view>
								<uni-badge :text="item.count" type="error" size="small"></uni-badge>
							</view>
						</view>
					</view>
				</uni-swipe-action-item>
			</uni-swipe-action>
		</scroll-view>
		<u-empty mode="message" v-if="chatList.length==0" style="position: absolute;top: 35%;left: 36%;"></u-empty>
		<u-no-network></u-no-network>
	</view>
</template>

<script>
	let that
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	import uniSwipeAction from '@/components/uni-swipe-action/uni-swipe-action.vue'
	import uniSwipeActionItem from '@/components/uni-swipe-action-item/uni-swipe-action-item.vue'
	export default {
		computed: {
			...mapGetters(['APPTheme', 'userInfo', 'api']),
			computeContent(){
				return (res)=>{
					if(res.messageType=='voice'){//语音
						return '[语音]'
					}else if(res.messageType=='img'){//图片
						return '[图片]'
					}else if(res.messageType=='redEnvelope'){//红包
						return '[红包]'
					}else if(res.messageType=='video'){//视频
						return '[视频]'
					}else{
						return '[文字]'
					}
				}
			},
			computedUserInfo(){
				return (item)=>{
					let user=''
					if(item.name){
						user=item.name.slice(item.name.length-2,item.name.length);
					}
					
					return user
				}
			},
			//计算时间（解决ios时间转换问题）
			computeTime(){
				let that = this
				return (item) => {
					let reg=new RegExp('-','g')//g代表全部
					let createDate =item.time.replace(reg,"/");
					let time=new Date(createDate).getTime()
					return that.$lizhao.timeFrom(time,'yyyy-mm-dd hh:MM:ss')
				}
			}
		},
		components: {
			uniSwipeAction,
			uniSwipeActionItem
		},
		data() {
			return {
				showActionUuid:'',
				chatList:[],
				action:{
					src:'',
					list:[],
					options: [{
						text: '置顶',
						style: {
							backgroundColor: '#888'
						}
					}, {
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}],
					options1: [{
						text: '取消置顶',
						style: {
							backgroundColor: '#888'
						}
					}, {
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}]
				},
				refres:{//下拉刷新
					isRefresher:false
				},
				Topp:{
					list:[],//置顶人列表
					msgList:[],//置顶消息列表
				},
				AllCount:0//总未读数
			}
		},
		onLoad() {
			that = this
			//监听全局消息
			uni.$off('pages_IM_count')
			uni.$on('pages_IM_count',res=>{
				//查询未读消息列表
				that.getUnreadMsgList()
			})
			//获取置顶人信息
			that.getStorageSyncFn()
		},
		onShow() {
			//#ifdef APP-PLUS
			that.openDatabase()
			//查询未读消息列表
			that.getUnreadMsgList()
			//#endif
		},
		methods: {
			//打开数据库
			openDatabase(){
				//判断数据库是否打开
				let onoff=that.$lizhao.lzsqlite.isOpenDatabase()
				if(!onoff){//打开数据库
					that.$lizhao.lzsqlite.openDatabase().then(res=>{})
				}
			},
			//获取置顶人信息
			getStorageSyncFn(){
				try{
					that.Topp.list=uni.getStorageSync('topping_msg')||[]
				}catch(e){
					//TODO handle the exception
					that.Topp.list=[]
				}
			},
			//过滤掉隐藏的消息，并把置顶消息标记出来
			filterShowData(){
				that.chatList=that.chatList.filter((item)=>{
					if(that.Topp.list.includes(item.userId)){//标记置顶信息
						item.isTop=true
					}else{
						item.isTop=false
					}
					//过滤掉隐藏的消息
					return item.isMsgShow==1
				})
				//动态获取备注的名字
				that.remarksNameFn()
				//标记tabbar角标
				that.setTabbarCorner()
			},
			//标记tabbar角标
			setTabbarCorner(){
				uni.setStorageSync('tabbarAllCount',that.AllCount)
				if(uni.getStorageSync('tabbarAllCount')!==0){
					uni.setTabBarBadge({
					  index: 3,
					  text: ''+uni.getStorageSync('tabbarAllCount')
					})
				}else{
					uni.removeTabBarBadge({index: 3})
				}
			},
			//动态获取备注的名字
			remarksNameFn(){
				that.chatList.forEach((item)=>{
					that.getReceiveInfoFn(item)
				})
			},
			//获取用户信息
			getReceiveInfoFn(item){
				that.GLOBAL.doGet(that.api.GLOBAL_rest_sys_user_findUserById,{id:item.userId}).then(res=>{
					if(res.code=='0'){
						item.userInfo=res.data
					}
				}).catch(err=>{
					console.log('获取用户信息失败');
				})
			},
			//查询所有消息列表【我发送的和发给我的】
			getUnreadMsgList(){
				that.$lizhao.lzsqlite.selectUnreadMsg().then(res=>{
					// console.log('查询所有消息结果',res);
					if(res.code=='0'){
						let arr=res.data.filter(rs=>{
							if(rs.receiveId!=JSON.parse(that.userInfo).id){
								//数据交换
								[rs.userId,rs.receiveId]=[rs.receiveId,rs.userId]
								try{
									rs.userInfo=JSON.parse(rs.receiveInfo)
								}catch(e){
									//TODO handle the exception
								}
							}else{
								try{
									rs.userInfo=JSON.parse(rs.userInfo)
								}catch(e){
									//TODO handle the exception
								}
							}
							
							//过滤掉系统消息
							if(rs.type!='system'){
								return rs
							}
						})
						// console.log('交换过的数据',arr);
						//计算过滤结果
						that.computerResult(arr)
					}
					
				})
			},
			computerResult(data){
				//拿到所有消息用户id
				let allUserIds=data.map(res=>{
					return res.userId
				})
				//数组去重后
				var allUserIds2 = allUserIds.filter((x, index,self)=>self.indexOf(x)===index)
				let arr=[]
				let allNum=0
				for(let a=0;a<allUserIds2.length;a++){
					let countList=data.filter(res=>{
						if(res.userId==allUserIds2[a]){
							return res
						}
					})
					//获取未读消息总条数
					let count= that.getUnreadCount(data,allUserIds2[a])
					console.log('获取每个人未读消息总条数',count);
					allNum+=count
					that.AllCount=allNum//所有人总共的未读
					let req={
						...countList[countList.length-1],//对方发给我的最后一条消息
						//未读消息条数
						count:count
					}
					arr.push(req)
				}
				that.chatList=arr
				//过滤掉隐藏的消息，并把置顶消息标记出来
				that.filterShowData()
				
			},
			//获取未读消息总条数
			getUnreadCount(data,userId){
				//拿到所有未读消息
				let userIds=data.filter(res=>{
					if(res.isRead==0&&res.userId==userId){
						return res.userId
					}
				})
				console.log('拿到所有未读消息',userIds);
				//数组去重后,拿到发送者id数组
				var userIds2 = userIds.filter((x, index,self)=>self.indexOf(x)===index)  
				return userIds2.length
			},
			//获取本地数据库聊天消息
			getSqChatData(receiveId, successCallback, errorCallback){
				//查询数据
				that.$lizhao.lzsqlite.getPageLimit({pageSize:2,pageNum:1,receiveId:receiveId}).then(res=>{
					if(res.code=='0'){
						let content=res.data[res.data.length-1].content
						if(JSON.parse(content).text=='用户不在线，已离线发送'){
							successCallback&&successCallback(res.data[res.data.length-2])
						}else{
							successCallback&&successCallback(res.data[res.data.length-1])
						}
					}else{
						errorCallback&&errorCallback('失败了')
					}
				})
			},
			//跳转
			navigetTo(item){
				uni.navigateTo({
					url: '/pages/IM/lz-chat/lz-chat?receiveId='+item.userId,
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			//下拉刷新
			loadRefresh(){
				if(that.refres.isRefresher){
					return ;
				}
				that.refres.isRefresher=true
				//查询未读消息列表
				that.getUnreadMsgList()
				that.$nextTick(function(){
					//结束下拉刷新
					that.refres.isRefresher=false
				})
			},
			//左滑
			actionItemClick(e,item){
				console.log(e,item);
				if(e.index==1){//删除
					//更新数据库，把最后一条记录的isMsgShow显示改为隐藏
					that.$lizhao.lzsqlite.changeSQDataFn(item.uuid,'isMsgShow',0).then(res=>{
						if(res.code=='0'){
							//查询未读消息列表
							that.getUnreadMsgList()
						}
					})
				}else if(e.index==0){//置顶
					that.showActionUuid=item.uuid//修复滑动option的text从【置顶】变为【取消置顶】界面错乱 解决思路先隐藏在显示重新渲染
					if(e.content.text=='置顶'){
						//把谁发给我的消息置顶
						that.Topp.list.push(item.userId)
						//数组去重
						var list = that.Topp.list.filter((x, index,self)=>self.indexOf(x)===index)
						// //存储置顶人信息
						uni.setStorageSync('topping_msg', list);
					}else{//取消置顶
						var list = that.Topp.list.filter((x)=>{
							return x!=item.userId
						})
						// //存储置顶人信息
						uni.setStorageSync('topping_msg', list);
					}
					//获取置顶人信息
					that.getStorageSyncFn()
					//过滤掉隐藏的消息，并把置顶消息标记出来
					that.filterShowData()
					//修改option的text之后显示当前的uni-swipe-action-item
					that.$nextTick(function(){
						that.showActionUuid=''
					})
				}
			}
			
		}

	}
</script>

<style scoped lang="scss">
	.im {
		height: 100%;display: flex;flex-direction: column;
		.center{
			flex: 1;
		}
		.center-list-item{
			display: flex;padding:5px;align-items: center;line-height: 20px;box-sizing: border-box;width: 100%;
			.item-left{
				width:40px;height: 40px;padding: 10px;display: flex;align-items: center;justify-content: center;position: relative;
				.text-warp{
					background: $bg-color;border-radius: 50%;width: 40px;height: 40px;font-size: 12px;display: flex;justify-content: center;align-items: center;color: #fff;
				}
			}
			.item-right{
				padding: 5px;font-size: 14px;box-sizing: border-box;width: 600rpx;
				.item-right-top{
					display: flex;justify-content: space-between;
					.top-date{
						color: #888;font-size: 10px;
					}
				}
				.item-right-bottom{
					display: flex;justify-content: space-between;
					.top-title{
						color: #888;font-size: 12px;
					}
				}
			}
		}
		// 置顶颜色
		.center-list-item-top{
			background-color: rgba($color: #0066CC, $alpha: 0.1);
		}
	}
</style>
